<?php
declare (strict_types=1);

namespace app\api\controller;

use app\api\model\wxapp\Setting as WxappSettingModel;
use app\api\service\User as UserService;
use app\common\library\wechat\WxApi;
use app\common\model\ChannelBrowseLog as ChannelBrowseLogModel;
use function Sodium\add;


/**
 * 渠道推广
 * Class help
 * @package app\store\controller\wxapp
 */
class Channel extends Controller
{
    /**
     * 生成微信二维码
     * @return \think\response\Json
     * @throws \cores\exception\BaseException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function wxcode()
    {
        $scene = $this->request->param('scene');
        if(empty($scene)){
            return $this->renderError('参数scene不能为空');
        }
        // 获取当前小程序信息
        $wxConfig = WxappSettingModel::getWxappConfig();
        // 微信登录 (获取session_key)
        $WxApi = new WxApi($wxConfig['app_id'], $wxConfig['app_secret']);
        $result = $WxApi->WxCode($scene);
        if($result['status_code'] == 200){
            echo '<img src="'.$result['img'].'" />';exit;
        }
        return $this->renderError('二维码生成失败');
    }

    /**
     * 用户通过渠道二维码浏览信息上报
     * @return \think\response\Json
     * @throws \cores\exception\BaseException
     */
    public function browseLog()
    {
        $channelName = $this->request->post('channelName');
        if(empty($channelName)){
            return $this->renderSuccess([], '邦豆百货用户');
        }
        $data['user_agent'] = isset($_SERVER['HTTP_USER_AGENT']) ? trim($_SERVER['HTTP_USER_AGENT']) : "";
        $data['user_id'] = '';
        $userinfo = UserService::getCurrentLoginUser();
        if(isset($userinfo['user_id'])){
            $data['user_id'] = $userinfo['user_id'];
        }
        $data['channel_platform'] = $channelName;
        $data['create_time'] = time();
        $channelBrowseLogModel = new ChannelBrowseLogModel();
        $data['store_id'] = $channelBrowseLogModel::$storeId;
        $result = $channelBrowseLogModel->save($data);
        if($result){
            return $this->renderSuccess([], '用户浏览日志上报成功');
        }
        return $this->renderError('用户浏览日志上报失败');
    }
}
